package com.platform.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.platform.dao.CartDao;
import com.platform.dao.GoodsDao;
import com.platform.dao.ProductDao;
import com.platform.entity.CartEntity;
import com.platform.entity.GoodsEntity;
import com.platform.entity.ProductEntity;
import com.platform.entity.UserEntity;

/**
 * 
 * 
 * @author lipengjun
 * @email 939961241@qq.com
 * @date 2017-08-13 10:41:06
 */
@Service("cartService")
public class CartService {
	@Autowired
	private CartDao cartDao;
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private ProductDao productDao;

	public CartEntity queryObject(Integer id){
		return cartDao.queryObject(id);
	}
	
	public List<CartEntity> queryList(Map<String, Object> map){
		return cartDao.queryList(map);
	}
	
	public int queryTotal(Map<String, Object> map){
		return cartDao.queryTotal(map);
	}
	
    @Transactional
	public void save(CartEntity cart){
		if(cart.getId() == null)
			cartDao.save(cart);
		else
			cartDao.update(cart);
	}
	
    @Transactional
	public CartEntity addCartProduct(Integer productId,Integer buyNum,UserEntity user){
    	ProductEntity product = productDao.queryObject(productId);
    	GoodsEntity goods = goodsDao.queryObject(product.getGoodsId());
    	if(goods.isPrivilege()) {//0:文章   3:音频  4:视频  一份即可
    		buyNum = 1;
    	}
    	Map<String, Object> params = new HashMap<String,Object>();
    	params.put("userId", user.getId());
    	params.put("productId", product.getId());
    	List<CartEntity> carts = cartDao.queryList(params);
    	CartEntity cart;
    	if(carts.size() == 1) {
    		cart = carts.get(0);
    	}else {
        	cart = new CartEntity();
    	}
    	cart.setProduct(product);
    	cart.setListPicUrl(goods.getListPicUrl());
    	cart.setUserId(user.getId());
    	cart.setChecked(1);
    	cart.addNumber(buyNum);
    	if(cart.getId() == null)
    		cartDao.save(cart);
    	else
    		cartDao.update(cart);
    	return cart;
	}
    
	public void update(CartEntity cart){
		cartDao.update(cart);
	}
	
	public void delete(Integer id){
		cartDao.delete(id);
	}
	
	public void deleteBatch(Integer[] ids){
		cartDao.deleteBatch(ids);
	}
	
	public void updateCheckByCartId(Map<String, Object> map) {
		cartDao.updateCheckByCartId(map);
	}

	
	public void updateCheckByUserId(Map<String, Object> map) {
		cartDao.updateCheckByUserId(map);
	}
	
	public void updateBuyNum(Map<String, Object> map) {
		cartDao.updateBuyNum(map);
	}

}
